package com.sixth.aspect;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sixth.bean.common.BasePageInfo;
import com.sixth.bean.common.BasePageInfoVo;
import com.sixth.constant.Constant;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @ClassName PageInfoAspect
 * @Description TODO
 * @Author XiaoWJ
 * @Date 2022/9/7 16:25
 **/

// 分页方法的切面

@Aspect
@Component
public class PageInfoAspect {

    // 指定切入点为@PageInfoAdvice注解
    @Pointcut("@annotation(com.sixth.annotation.PageInfoAdvice)")
    public void servicePointcut(){}

    // 指定around通知的切入点
    @Around("servicePointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取目标方法的参数
        Object[] args = joinPoint.getArgs();
        // 找到参数类型为BasePageInfo类型的参数
        BasePageInfo basePageInfo = null;
        for (Object arg : args) {
            if(arg instanceof BasePageInfo){
                basePageInfo = ((BasePageInfo) arg);
                break;
            }
        }

        // 开启分页
        Integer page = basePageInfo.getPage();
        Integer limit = basePageInfo.getLimit();
        PageHelper.startPage(page, limit);
        //list数组使用Object接收
        //执行委托类方法，获得的数据库查询结果
        List<Object> proceed = (List<Object>)joinPoint.proceed();


        PageInfo<Object> info = new PageInfo<>(proceed);
        BasePageInfoVo<Object> basePageInfoVo =
                new BasePageInfoVo<>(info.getTotal(),info.getPages(),limit,page,proceed);

        return basePageInfoVo;

    }
}
